package cn.ac.ucas.service;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.ac.ucas.conn.Conn;
import cn.ac.ucas.model.Contents;

public class ContentService {
	private Connection conn;
	private PreparedStatement pstmt;

	public ContentService() {
		conn = new Conn().getConn();

	}

	public boolean addCon(Contents  contents ) {
		try {
			pstmt = conn.prepareStatement(
					"insert into contents(title,contents,fwdate)"
							+ "values(?,?,?)");
			pstmt.setString(1, contents.getTitle());
			pstmt.setString(2, contents.getContents());	
			pstmt.setString(3, contents.getFwdate());	
			
			pstmt.executeUpdate();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean updateCon(Contents  contents){
		
		try {
			pstmt=conn.prepareStatement("update Student set title=?,contents=?,fwdate=? where id=?");
			pstmt.setString(1, contents.getTitle());
			pstmt.setString(2, contents.getContents());	
			pstmt.setString(3, contents.getFwdate());	
			
			pstmt.executeUpdate();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public List getAllCon() {
		List conList = new ArrayList();
		try {
			pstmt = conn.prepareStatement("select * from contents  order by id desc");
			ResultSet rst = pstmt.executeQuery();
			while (rst.next()) {
				Contents con = new Contents();
				con.setId(rst.getInt(1));
				con.setTitle(rst.getString(2));
				con.setContents(rst.getString(3));
				con.setFwdate(rst.getString(4));
				conList.add(con);

			}

			return conList;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public boolean deleteCon(int id) {

		try {
			pstmt = conn.prepareStatement("delete from Contents where id=?");
			pstmt.setInt(1, id);
			pstmt.executeUpdate();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

	}

	public Contents getConById(int id) {
		try {
			pstmt = conn.prepareStatement("select * from Student where id = ?");
			pstmt.setInt(1, id);
			ResultSet rst = pstmt.executeQuery();
			
			if(rst.next()){
				Contents con = new Contents();
				con.setId(rst.getInt(1));
				con.setTitle(rst.getString(2));
				con.setContents(rst.getString(3));
				con.setFwdate(rst.getString(4));
				return con;
			}
			
			return null;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}
  
	
}
